<?php
namespace app\api\service\uniapp\order;

use app\api\controller\Huada;
use app\api\controller\uniapp\Order;
use app\api\model\Region;
use app\api\model\ShopPayOrder;
use app\api\model\ShopPayOrderGoods;
use app\api\model\ShopYiwu;
use app\api\model\Users;
use app\api\model\UserStore;
use app\common\controller\Api;
use think\Db;
use think\Response;
use addons\qrcode\library\Service as QrcodeService;

class OrderService extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function createOrder($from_uid,$to_uid,$money,$benefit_type){
        $result=array();
        //两个互转id一样
        if($from_uid==$to_uid){
            $result['code']=-1;
            $result['msg']="不能支付给自己";
            return $result;
        }

        $fuser=Users::where(array('user_id'=>$from_uid,'is_lock'=>0))->find();
        $tuser=Users::where(array('user_id'=>$to_uid,'is_lock'=>0))->find();
        $shop=UserStore::where(array('user_id'=>$to_uid,'is_check'=>1))->find();
        if(!$fuser){
            $result['code']=-2;
            $result['msg']="支付用户不存在或已经被锁定";
            return $result;
        }
        if(!$shop){
            $result['code']=-3;
            $result['msg']="转入账号不是商家或审核没通过";
            return $result;
        }
        if(!$tuser){
            $result['code']=-4;
            $result['msg']="接收用户不存在或已经被锁定";
            return $result;
        }

        Db::startTrans();
        $trans_ok=true;

        //生成总订单
        $torder['user_id']=$from_uid;
        $torder['order_sn']=get_order_sn();
        $torder['shop_user_id']=$to_uid;
        $torder['order_money']=$money;
        $torder['remark']='支付总订单';
        $torder['status']=0;
        $torder['order_type']=6;
        $torder['create_time']=time();
        $torderadd=ShopPayOrder::create($torder,true);
        if(!$torderadd){
            $trans_ok = false;
        }
        //转账先以消费券为主，消费券不足则调用微信支付
        if($fuser['ywq']>=$money){ //消费券够付
            //生成店铺订单
            $data['user_id']=$from_uid;
            $data['order_sn']=get_order_sn();
            $data['shop_user_id']=$to_uid;
            $data['money']=$money;
            $data['order_money']=$money;
            $data['money_type']=6;
            $data['remark']='支付订单';
            $data['status']=1;
            $data['order_type']=1;
            $data['create_time']=time();
            $data['total_order_id']=$torderadd->id;

            $shopadd=ShopPayOrder::create($data,true);

            if($shopadd){
                //进行支付
                $ok1 = new_finance_record_and_add_money($from_uid,$money,6,2,203,$shopadd->id,$data['order_sn']);
                if(!$ok1){
                    $trans_ok=false;
                }
            }else{
                $trans_ok=false;
            }
            if($trans_ok){
                //标志总订单为已支付
                $torderok = ShopPayOrder::where("id",$torderadd->id)->update([
                    'status'=>1,
                    'pay_time'=>time(),
                    'finish_time'=>time(),
                ]);
                //进行语音播报
                if(!empty($shop['deviceName'])){
                    log_result("huada","语音播报-订单号：".$data['order_sn']);
                    $huada = new Huada();
                    $huada->send_voice($shop['deviceName'],0,$money*100,2,"收到消费券付款".$money."元");
                }
                Db::commit();
                //进行分成
                new_award($shopadd->id);

                $result['code']=2;
                $result['tuser_id']=$tuser['user_id'];
                $result['money']=$money;
                $result['msg']="支付成功";
            }else{
                Db::rollback();
                $result['code']=-9;
                $result['msg']="支付失败";
            }
            return $result;
        }else{ //消费券不足支付
            $wxmoney = $money;
            if($fuser['ywq']>0.01){
                $payywq = intval($fuser['ywq']*100)/100;
                $wxmoney = bcadd(bcmul($money-$payywq, 100, 2), '0', 0)/100;
                //生成店铺订单
                $data['user_id']=$from_uid;
                $data['order_sn']=get_order_sn();
                $data['shop_user_id']=$to_uid;
                $data['money']=$payywq;
                $data['order_money']=$payywq;
                $data['money_type']=6;
                $data['remark']='支付订单';
                $data['status']=0;
                $data['order_type']=1;
                $data['create_time']=time();
                $data['total_order_id']=$torderadd->id;

                $shopadd=ShopPayOrder::create($data,true);
                if(!$shopadd){
                    $trans_ok = false;
                }
            }
            //生成微信支付订单
            //生成店铺订单
            $wxdata['user_id']=$from_uid;
            $wxdata['order_sn']=get_order_sn();
            $wxdata['shop_user_id']=$to_uid;
            $wxdata['money']=$wxmoney;
            $wxdata['order_money']=$wxmoney;
            $wxdata['money_type']=1;
            $wxdata['remark']='支付订单';
            $wxdata['status']=0;
            $wxdata['order_type']=1;
            $wxdata['create_time']=time();
            $wxdata['total_order_id']=$torderadd->id;
            $wxdata['benefit_type']=$benefit_type;
            if($shop['money_type']==2){
                $wxdata['merchant_id'] = $shop['merchant_id'];
            }else{
                $wxdata['merchant_id'] = config("leshua.merchant_id");
            }
            $wxdata['shop_money_type']=$shop['money_type'];
            $shopadd2=ShopPayOrder::create($wxdata,true);
            if(!$shopadd2){
                $trans_ok=false;
            }

            if($trans_ok){
                Db::commit();
                $result['code']=1;
                $result['tuser_id']=$tuser['user_id'];
                $result['money']=$wxmoney;
                $result['order_sn']=$wxdata['order_sn'];
                $result['msg']="跳转到微支付";
            }else{
                Db::rollback();
                $result['status']=-8;
                $result['msg']="支付出错";
            }
            return $result;
        }
    }

    public function createShoppingOrder($user_id,$goods_id,$pay_sum,$money,$address_id){
        $user = Users::where('user_id',$user_id)->find();
        if(!$user){
            return tok(-1,'用户不存在');
        }
        $goods = ShopYiwu::where('id',$goods_id)->find();
        if(!$goods){
            return tok(-2,'商品不存在');
        }
        $shop = UserStore::where('id',$goods['shop_id'])->find();
        if(!$shop){
            return tok(-3,'店铺不存在');
        }
        $total_money = round($goods['shop_price']*$pay_sum,2);
        if($total_money!=$money){
            return tok(-4,'订单金额不一致');
        }
        if($pay_sum>$goods['xiangou']&&$goods['xiangou']>0){
            return tok(-5,'超出每人限购数量');
        }
        if($goods['store_count']<$pay_sum){
            return tok(-6,'库存不足');
        }
        if($goods['is_vip']==1){
            //如果是VIP商品，购买人必须要有推荐人才能购买
            if($user['first_leader']<=0){
                return tok(-7,'购买vip商品必须有推荐人');
            }
        }

        Db::startTrans();
        $trans_ok=true;

        //生成总订单
        $torder['user_id']=$user_id;
        $torder['order_sn']=get_order_sn();
        $torder['shop_user_id']=$shop['user_id'];
        $torder['activity_id']=$goods['id'];
        $torder['buy_num']=$pay_sum;
        $torder['order_money']=$money;
        $torder['address_id']=$address_id;
        $torder['remark']=$goods['title'];
        $torder['status']=0;
        $torder['hexiao_code']=get_order_sn(3);
        $torder['order_type']=7;
        $torder['create_time']=time();
        $torderadd=ShopPayOrder::create($torder,true);
        if(!$torderadd){
            $trans_ok = false;
        }

        //生成订单商品
        $orderGoodsItem['order_id'] = $torderadd->id;
        $orderGoodsItem['goods_id'] = $goods['id'];
        $orderGoodsItem['goods_name'] = $goods['title'];
        $orderGoodsItem['goods_pic'] = $goods['thumb_pic'];
        $orderGoodsItem['goods_num'] = $pay_sum;
        $orderGoodsItem['goods_price'] = $goods['shop_price'];
        $orderGoodsItem['total_price'] = bcmul($pay_sum,$goods['shop_price'],2);
        $orderGoodsItem['ratio'] = $goods['ratio'];
        $orderGoodsItem['bargain_price'] = $goods['bargain_price'];
        $orderGoodsItem['createtime'] = time();
        $orderGoodsOk = ShopPayOrderGoods::create($orderGoodsItem,true);

        if(!$orderGoodsOk){
            $trans_ok = false;
        }

        //转账先以消费券为主，消费券不足则调用微信支付
        if($user['ywq']>=$money){ //消费券够付
            //生成店铺订单
            $data['user_id']=$user_id;
            $data['order_sn']=get_order_sn();
            $data['shop_user_id']=$shop['user_id'];
            $data['activity_id']=$goods_id;
            $data['buy_num']=$pay_sum;
            $data['money']=$money;
            $data['order_money']=$money;
            $data['money_type']=6;
            $data['remark']=$goods['title'];
            $data['status']=1;
            $data['order_type']=1;
            $data['create_time']=time();
            $data['pay_time']=time();
            $data['address_id']=$address_id;
            $data['total_order_id']=$torderadd->id;
            $shopadd=ShopPayOrder::create($data,true);

            if($shopadd){
                //进行支付
                $ok1 = new_finance_record_and_add_money($user_id,$money,6,2,203,$shopadd->id,$data['order_sn']);
                if(!$ok1){
                    $trans_ok=false;
                }
            }else{
                $trans_ok=false;
            }
            if($trans_ok){
                //标志总订单为已支付
                $torderok = ShopPayOrder::where("id",$torderadd->id)->update([
                    'status'=>1,
                    'money_type'=>6,
                    'pay_time'=>time(),
                    'finish_time'=>time(),
                ]);
                Db::commit();

                $result['code']=2;
                $result['tuser_id']=$user_id;
                $result['money']=$money;
                $result['msg']="支付成功";
            }else{
                Db::rollback();
                $result['code']=-9;
                $result['msg']="支付失败";
            }
            return $result;
        }else{ //消费券不足支付
            $wxmoney = $money;
            if($user['ywq']>0.01){
                $payywq = intval($user['ywq']*100)/100;
                $wxmoney = bcadd(bcmul($money-$payywq, 100, 2), '0', 0)/100;
                //生成店铺订单
                $data['user_id']=$user_id;
                $data['order_sn']=get_order_sn();
                $data['shop_user_id']=$shop['user_id'];
                $data['activity_id']=$goods_id;
                $data['buy_num']=$pay_sum;
                $data['money']=$payywq;
                $data['order_money']=$payywq;
                $data['money_type']=6;
                $data['remark']=$goods['title'];
                $data['status']=0;
                $data['order_type']=4;
                $data['create_time']=time();
                $data['pay_time']=time();
                $data['address_id']=$address_id;
                $data['total_order_id']=$torderadd->id;

                $shopadd=ShopPayOrder::create($data,true);
                if(!$shopadd){
                    $trans_ok = false;
                }
            }
            //生成微信支付订单
            //生成店铺订单
            $wxdata['user_id']=$user_id;
            $wxdata['order_sn']=get_order_sn();
            $wxdata['shop_user_id']=$shop['user_id'];
            $wxdata['money']=$wxmoney;
            $wxdata['order_money']=$wxmoney;
            $wxdata['money_type']=1;
            $wxdata['remark']=$goods['title'];
            $wxdata['status']=0;
            $wxdata['order_type']=4;
            $wxdata['create_time']=time();
            $wxdata['total_order_id']=$torderadd->id;
            if($shop['money_type']==2){
                $wxdata['merchant_id'] = $shop['merchant_id'];
            }else{
                $wxdata['merchant_id'] = config("leshua.merchant_id");
            }
            $wxdata['shop_money_type']=$shop['money_type'];
            $shopadd2=ShopPayOrder::create($wxdata,true);
            if(!$shopadd2){
                $trans_ok=false;
            }

            if($trans_ok){
                Db::commit();
                $result['code']=1;
                $result['tuser_id']=$user_id;
                $result['money']=$wxmoney;
                $result['order_sn']=$wxdata['order_sn'];
                $result['msg']="跳转到微支付";
            }else{
                Db::rollback();
                $result['status']=-9;
                $result['msg']="支付出错";
            }
            return $result;
        }
    }

    /**
     * 根据订单号获取订单
     * @param $ordersn 订单号
     * @param bool $checkuser 是否检查订单与登陆用户
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderBySn($ordersn,$checkuser=true){
        $user = session('authuser');
        $order = ShopPayOrder::where('order_sn',$ordersn)->find();
        if(!$order){
            return null;
        }
        if($checkuser&&$order['user_id']!=$user['user_id']){
            return null;
        }
        return $order;
    }

    /**
     * 根据订单id获取订单
     * @param $orderid 订单id
     * @param bool $checkuser 是否检查订单与登陆用户
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderById($orderid,$checkuser=true){
        $user = session('authuser');
        $order = ShopPayOrder::where('id',$orderid)->find();
        if(!$order){
            return null;
        }
        if($checkuser&&$order['user_id']!=$user['user_id']){
            return null;
        }
        return $order;
    }

    /**
     * 根据总订单id获取支付订单
     * @param $total_order_id 总订单id
     * @param $money_type 1=获取现金订单，6=获取消费券订单
     * @return array
     */
    public function getOrderByTotalOrderId($total_order_id,$money_type){
        $order = ShopPayOrder::where(['total_order_id'=>$total_order_id,'money_type'=>$money_type])->find();
        if(!$order){
            return null;
        }
        return $order;
    }
}